package com.fuershiye.woman.monitor.controller;

import com.fuershiye.woman.monitor.beans.*;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.model.Area;
import com.fuershiye.woman.monitor.service.AreaService;
import com.fuershiye.woman.monitor.service.UserService;
import com.fuershiye.woman.monitor.utils.ObjectUtil;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * 传统区域的管理
 * 
 * @author yongyongdong
 *
 */
@Controller
@RequestMapping(value = "/area")
@SuppressWarnings("unchecked")
public class AreaController {

	private static final Logger logger = LoggerFactory
			.getLogger(AreaController.class);

	@Autowired
	AreaService areaService;
	@Autowired
	UserService userService;

//	@RequiresPermissions("area:view")
	@RequestMapping(value = "/view.do")
	public String view(String page, Model model) {
		
		List<IdNamePid> areaList = areaService.getAllNames();
    	model.addAttribute("areaList", areaList);
    	
		return "area/" + page;
	}

//	@RequiresPermissions("area:list")
	@RequestMapping(value = "/list.do")
	@ResponseBody
	public Result list(String name, Long pid, Integer level, Integer page, Integer pageSize) {

		int status = 1;

		List<Area> areaList = areaService.list(name, pid, level, status, new Page(page, pageSize));
		int count = areaService.getTotal(name, pid, level, status);
		List<IdNamePid> areaAll = areaService.getAllNames();

		List<ViewArea> result = Lists.newArrayList();
		for (Area area: areaList) {
			if(area==null){
				continue;
			}
			ViewArea viewArea = new ViewArea();
			viewArea.setId(area.getId());
			viewArea.setCode(area.getCode());
			viewArea.setLevel(area.getLevel());
			viewArea.setName(area.getName());
			viewArea.setPid(area.getPid());
			if(area.getPid()==null||area.getPid()==0){
				viewArea.setPname("");
			}else {
				viewArea.setPname(ObjectUtil.getNameById(area.getPid(), areaAll));
			}
			result.add(viewArea);
		}

		return new Result(Massage.SUCCESS, new PageResult(result, count));
	}

//	@RequiresPermissions("area:save")
	@RequestMapping(value = "/save.do")
	@ResponseBody
	public Result save(Long id, String name, String code, Long pid, Integer level) {

		Area area = null;
		boolean add = false;
		if (id == null || id == 0) {
			add = true;
			area = new Area();
		} else {
			area = areaService.get(id);
			if (area == null) {
				logger.error("AreaController update,area is null");
				return new Result(Massage.AREA_IS_NULL);
			}
		}

		area.setCode(code);
		area.setName(name);
		area.setLevel(level);
		area.setPid(pid);
		area.setMtime(new Date());
		area.setStatus(1);

		areaService.save(area);

		// 如果是新加的则给默认的排序号sort(主键id)
		if (add) {
			Area top = areaService.getTop();
			if (top != null) {
				area.setSort(top.getId());
				area.setCtime(new Date());
				areaService.save(area);
				return new Result(Massage.SUCCESS);
			} else {
				logger.error("AreaController add is null");
				return new Result(Massage.AREA_IS_NULL);
			}
		}
		return new Result(Massage.SUCCESS);
	}

	/**
	 * @param id
	 *            要排序的数据
	 * @param aim
	 *            1:升序; 2:降序
	 * @return
	 */
//	@RequiresPermissions("area:sort")
	@RequestMapping(value = "/sort.do")
	@ResponseBody
	public boolean sort(Long id, Integer aim) {

		if (id == null || (aim != 1 && aim != 2)) {
			logger.info("AreaController sort id null, id:{},aim:{}", id, aim);
			return false;
		}
		Area it = areaService.get(id);
		if (it == null) {
			logger.error("AreaController it is null, id:{}", id);
			return false;
		}

		Area top = areaService.findBySort(it.getSort(), aim, 1);
		if (top == null) {
			// 查不到需要交换的对象,则认为交换成功
			return true;
		}
		// 交换序号
		long temp = it.getSort();
		it.setSort(top.getSort());
		top.setSort(temp);
		// 保存
		areaService.save(it);
		areaService.save(top);
		return true;
	}

//	@RequiresPermissions("area:delete")
	@RequestMapping(value = "/delete.do")
	@ResponseBody
	public boolean delete(Long id) {
		Area area = areaService.get(id);
		area.setStatus(0);// 修改为已删除
		areaService.save(area);
		return true;
	}
	
//	@RequiresPermissions("area:samePid")
	@RequestMapping(value = "/samePid.do")
	@ResponseBody
	public List<IdNamePid> getSamePid(Integer level, Long pid) {
		
		return areaService.getByLevelAndPid(level, pid);
	}
	
	//query
	//	@RequiresPermissions("area:samePid")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/allCity.do")
	@ResponseBody
	public Result getAllCity() {
		
		//地域级别 1：国家;2:省，直辖市;3:地级;4:区县;5:乡镇级;6:其他
		Integer level = 3;
		
		return new Result(Massage.SUCCESS, areaService.getIdNameByLevelAndPid(level, null));
	}


}
